package com.gzg.userservice.interceptor;

import com.gzg.userservice.utils.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RegisterInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null) {
            ip = request.getRemoteAddr();
        }
        // 检查是否为 IPv6 地址
        if (ip.contains(":")) {
            // 尝试提取 IPv4 地址
            int ipv4StartIndex = ip.lastIndexOf(":") + 1;
            ip = ip.substring(ipv4StartIndex);
            // 验证是否为有效的 IPv4 地址
            if (!ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
                ip = "0.0.0.0"; // 如果无效，设置为默认值
            }
        }//AI生成
        UserContext.setIp(ip);
        return true;
    }
}
